import Router from "koa-router";
import { authMiddleware } from "../../../middleware/auth";
import { pool } from "../../../config/database";
import { RowDataPacket, ResultSetHeader } from "mysql2";
import { 
  checkAdminPermission, 
  getPaginationParams, 
  createPaginatedResponse, 
  getSearchParams,
  handleError,
  successResponse,
  validateId,
  validateBatchIds
} from "../common";

const router = new Router({ prefix: "/api/admin/orders" });

// 获取订单列表 - 支持搜索和分页
router.get("/", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { page, limit, offset } = getPaginationParams(ctx);
    const { keyword, status, paymentStatus, startDate, endDate, minAmount, maxAmount } = getSearchParams(ctx);

    // 构建查询条件
    let whereClause = "WHERE 1=1";
    const params: any[] = [];

    if (keyword) {
      whereClause += " AND (o.order_no LIKE ? OR u.username LIKE ? OR u.email LIKE ?)";
      const searchTerm = `%${keyword}%`;
      params.push(searchTerm, searchTerm, searchTerm);
    }

    if (status) {
      whereClause += " AND o.status = ?";
      params.push(status);
    }

    if (paymentStatus) {
      whereClause += " AND o.payment_status = ?";
      params.push(paymentStatus);
    }

    if (minAmount) {
      whereClause += " AND o.final_price >= ?";
      params.push(parseFloat(minAmount as string));
    }

    if (maxAmount) {
      whereClause += " AND o.final_price <= ?";
      params.push(parseFloat(maxAmount as string));
    }

    if (startDate) {
      whereClause += " AND o.created_at >= ?";
      params.push(startDate);
    }

    if (endDate) {
      whereClause += " AND o.created_at <= ?";
      params.push(endDate + ' 23:59:59');
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM orders o 
       JOIN users u ON o.user_id = u.id 
       ${whereClause}`,
      params
    ) as [RowDataPacket[], any];
    const total = countResult[0].total;

    // 获取订单列表
    const [orders] = await pool.execute(`
      SELECT 
        o.id, o.order_no, o.user_id, o.final_price as total_amount, o.status, 
        o.payment_status, o.payment_method, o.shipping_address, 
        o.created_at, o.updated_at,
        u.username, u.email, u.nickname
      FROM orders o
      JOIN users u ON o.user_id = u.id
      ${whereClause}
      ORDER BY o.created_at DESC
      LIMIT ${limit} OFFSET ${offset}
    `, params) as [RowDataPacket[], any];

    // 组合数据
    const enrichedOrders = orders.map(order => {
      return {
        ...order,
        customerInfo: {
          username: order.username,
          email: order.email,
          nickname: order.nickname
        },
        orderStats: {
          quantity: order.quantity || 1,
          unitPrice: order.unit_price,
          totalPrice: order.total_price,
          finalPrice: order.final_price
        }
      };
    });

    const response = createPaginatedResponse(enrichedOrders, total, page, limit);
    successResponse(ctx, response, "获取订单列表成功");

  } catch (error) {
    handleError(ctx, error, "获取订单列表失败");
  }
});

// 获取订单详情
router.get("/:id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    // 获取订单基本信息
    const [orders] = await pool.execute(`
      SELECT 
        o.*, u.username, u.email, u.nickname, u.phone
      FROM orders o
      JOIN users u ON o.user_id = u.id
      WHERE o.id = ?
    `, [id]) as [RowDataPacket[], any];

    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "订单不存在" };
      return;
    }

    const order = orders[0];

    // 获取订单关联的产品信息
    let productInfo = null;
    if (order.product_id) {
      const [products] = await pool.execute(`
        SELECT id, name, images, category, price
        FROM products 
        WHERE id = ?
      `, [order.product_id]) as [RowDataPacket[], any];
      
      if (products.length > 0) {
        productInfo = products[0];
      }
    }

    // 获取配置信息
    let configInfo = null;
    if (order.config_id) {
      const [configs] = await pool.execute(`
        SELECT id, name, images, category, total_price as price
        FROM products 
        WHERE id = ?
      `, [order.config_id]) as [RowDataPacket[], any];
      
      if (configs.length > 0) {
        configInfo = configs[0];
      }
    }

    const orderDetail = {
      ...order,
      customerInfo: {
        username: order.username,
        email: order.email,
        nickname: order.nickname,
        phone: order.phone
      },
      productInfo,
      configInfo,
      // 解析收货地址
      shipping_address: order.shipping_address ? JSON.parse(order.shipping_address) : null,
      summary: {
        quantity: order.quantity || 1,
        unitPrice: order.unit_price,
        totalPrice: order.total_price,
        shippingFee: order.shipping_fee || 0,
        discountAmount: order.discount_amount || 0,
        finalPrice: order.final_price
      }
    };

    successResponse(ctx, orderDetail, "获取订单详情成功");

  } catch (error) {
    handleError(ctx, error, "获取订单详情失败");
  }
});

// 更新订单状态
router.put("/:id/status", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const { status, payment_status, notes } = ctx.request.body as {
      status?: string;
      payment_status?: string;
      notes?: string;
    };

    // 检查订单是否存在
    const [orders] = await pool.execute(
      "SELECT id, status, payment_status FROM orders WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "订单不存在" };
      return;
    }

    const currentOrder = orders[0];

    // 构建更新语句
    const updateFields: string[] = [];
    const updateValues: any[] = [];

    if (status !== undefined) {
      // 验证状态值
      const validStatuses = ['pending', 'confirmed', 'processing', 'shipped', 'delivered', 'cancelled', 'completed'];
      if (!validStatuses.includes(status)) {
        ctx.status = 400;
        ctx.body = { success: false, message: "无效的订单状态" };
        return;
      }
      updateFields.push("status = ?");
      updateValues.push(status);
    }

    if (payment_status !== undefined) {
      // 验证支付状态值
      const validPaymentStatuses = ['pending', 'paid', 'failed', 'refunded', 'partial_refund'];
      if (!validPaymentStatuses.includes(payment_status)) {
        ctx.status = 400;
        ctx.body = { success: false, message: "无效的支付状态" };
        return;
      }
      updateFields.push("payment_status = ?");
      updateValues.push(payment_status);
    }

    if (notes !== undefined) {
      updateFields.push("notes = ?");
      updateValues.push(notes);
    }

    if (updateFields.length === 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: "没有提供要更新的字段" };
      return;
    }

    updateFields.push("updated_at = NOW()");
    updateValues.push(id);

    // 执行更新
    await pool.execute(
      `UPDATE orders SET ${updateFields.join(", ")} WHERE id = ?`,
      updateValues
    );

    // 如果订单被取消，需要恢复库存
    if (status === 'cancelled' && currentOrder.status !== 'cancelled') {
      await restoreOrderStock(id);
    }

    // 获取更新后的订单信息
    const [updatedOrder] = await pool.execute(
      "SELECT * FROM orders WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    successResponse(ctx, updatedOrder[0], "订单状态更新成功");

  } catch (error) {
    handleError(ctx, error, "更新订单状态失败");
  }
});

// 恢复订单库存的辅助函数
async function restoreOrderStock(orderId: number) {
  try {
    // 获取订单商品
    const [orderItems] = await pool.execute(
      "SELECT product_id, quantity FROM order_items WHERE order_id = ? AND product_id IS NOT NULL",
      [orderId]
    ) as [RowDataPacket[], any];

    // 恢复每个商品的库存
    for (const item of orderItems) {
      await pool.execute(
        "UPDATE products SET stock_quantity = stock_quantity + ? WHERE id = ?",
        [item.quantity, item.product_id]
      );
    }
  } catch (error) {
    console.error('恢复订单库存失败:', error);
  }
}

// 批量更新订单状态
router.post("/batch-update-status", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const ids = validateBatchIds(ctx);
    if (ids === null) return;

    const { status, payment_status } = ctx.request.body as { 
      status?: string; 
      payment_status?: string;
    };

    if (!status && !payment_status) {
      ctx.status = 400;
      ctx.body = { success: false, message: "请提供要更新的状态" };
      return;
    }

    // 构建更新语句
    const updateFields: string[] = [];
    const updateValues: any[] = [];

    if (status) {
      const validStatuses = ['pending', 'confirmed', 'processing', 'shipped', 'delivered', 'cancelled', 'completed'];
      if (!validStatuses.includes(status)) {
        ctx.status = 400;
        ctx.body = { success: false, message: "无效的订单状态" };
        return;
      }
      updateFields.push("status = ?");
      updateValues.push(status);
    }

    if (payment_status) {
      const validPaymentStatuses = ['pending', 'paid', 'failed', 'refunded', 'partial_refund'];
      if (!validPaymentStatuses.includes(payment_status)) {
        ctx.status = 400;
        ctx.body = { success: false, message: "无效的支付状态" };
        return;
      }
      updateFields.push("payment_status = ?");
      updateValues.push(payment_status);
    }

    updateFields.push("updated_at = NOW()");

    // 执行批量更新
    const [result] = await pool.execute(
      `UPDATE orders SET ${updateFields.join(", ")} WHERE id IN (${ids.map(() => '?').join(',')})`,
      [...updateValues, ...ids]
    ) as [ResultSetHeader, any];

    successResponse(ctx, { 
      updatedCount: result.affectedRows,
      status,
      payment_status 
    }, `批量更新状态成功，影响${result.affectedRows}个订单`);

  } catch (error) {
    handleError(ctx, error, "批量更新状态失败");
  }
});

// 删除订单（软删除）
router.delete("/:id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    // 检查订单是否存在
    const [orders] = await pool.execute(
      "SELECT id, status FROM orders WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (orders.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "订单不存在" };
      return;
    }

    const order = orders[0];

    // 只允许删除已取消或已完成的订单
    if (!['cancelled', 'completed'].includes(order.status)) {
      ctx.status = 400;
      ctx.body = { success: false, message: "只能删除已取消或已完成的订单" };
      return;
    }

    // 软删除：更新状态为deleted
    await pool.execute(
      "UPDATE orders SET status = 'deleted', updated_at = NOW() WHERE id = ?",
      [id]
    );

    successResponse(ctx, { id }, "订单删除成功");

  } catch (error) {
    handleError(ctx, error, "删除订单失败");
  }
});

// 获取订单统计信息
router.get("/statistics/overview", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    // 订单总体统计
    const [orderStats] = await pool.execute(`
      SELECT 
        COUNT(*) as total_orders,
        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_orders,
        COUNT(CASE WHEN status = 'confirmed' THEN 1 END) as confirmed_orders,
        COUNT(CASE WHEN status = 'processing' THEN 1 END) as processing_orders,
        COUNT(CASE WHEN status = 'shipped' THEN 1 END) as shipped_orders,
        COUNT(CASE WHEN status = 'delivered' THEN 1 END) as delivered_orders,
        COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_orders,
        COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_orders,
        SUM(final_price) as total_revenue,
        AVG(final_price) as avg_order_value,
        COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as orders_this_week,
        COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as orders_this_month
      FROM orders WHERE status != 'deleted'
    `) as [RowDataPacket[], any];

    // 支付统计
    const [paymentStats] = await pool.execute(`
      SELECT 
        COUNT(CASE WHEN payment_status = 'pending' THEN 1 END) as pending_payments,
        COUNT(CASE WHEN payment_status = 'paid' THEN 1 END) as paid_orders,
        COUNT(CASE WHEN payment_status = 'failed' THEN 1 END) as failed_payments,
        COUNT(CASE WHEN payment_status = 'refunded' THEN 1 END) as refunded_orders,
        SUM(CASE WHEN payment_status = 'paid' THEN final_price ELSE 0 END) as paid_revenue
      FROM orders WHERE status != 'deleted'
    `) as [RowDataPacket[], any];

    // 每日订单统计（最近30天）
    const [dailyStats] = await pool.execute(`
      SELECT 
        DATE(created_at) as date,
        COUNT(*) as order_count,
        SUM(final_price) as daily_revenue
      FROM orders 
      WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        AND status != 'deleted'
      GROUP BY DATE(created_at)
      ORDER BY date DESC
    `) as [RowDataPacket[], any];

    // 热门商品统计
    const [topProducts] = await pool.execute(`
      SELECT 
        p.name as product_name,
        p.category,
        SUM(o.quantity) as total_sold,
        SUM(o.final_price) as total_revenue,
        COUNT(o.id) as order_count,
        AVG(o.final_price) as avg_price
      FROM orders o
      JOIN products p ON (o.product_id = p.id OR o.config_id = p.id)
      WHERE o.status NOT IN ('cancelled', 'deleted')
        AND (o.product_id IS NOT NULL OR o.config_id IS NOT NULL)
      GROUP BY p.id, p.name, p.category
      ORDER BY total_sold DESC
      LIMIT 10
    `) as [RowDataPacket[], any];

    successResponse(ctx, {
      orders: orderStats[0],
      payments: paymentStats[0],
      dailyStats,
      topProducts
    }, "获取订单统计成功");

  } catch (error) {
    handleError(ctx, error, "获取订单统计失败");
  }
});

export default router; 